<template>
	<div class="activeForm">
		<h3>form 表单验证</h3>
		<div class="form1">
			<h3>动态增减表单项</h3>
			<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic">
				<el-form-item prop="email" label="邮箱" :rules="[{ required: true, message: '请输入邮箱地址', trigger: 'blur' },{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }]">
					<el-input v-model="dynamicValidateForm.email"></el-input>
				</el-form-item>
				<el-form-item v-for="(domain, index) in dynamicValidateForm.domains" :label="'域名' + index" :key="domain.key" :prop="'domains.' + index + '.value'" :rules="{required: true, message: '域名不能为空', trigger: 'blur'}">
					<el-input v-model="domain.value"></el-input>
					<el-button @click.prevent="removeDomain(domain)">删除</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
					<el-button @click="addDomain">新增域名</el-button>
					<el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="form2">
			<h3>数字类型验证</h3>
			<el-form v-model="numberValidateForm" ref="numberValidateForm" label-width="100px">
				<el-form-item  label="年龄" prop="age" :rules="[{required:true,message:'年龄不能为空'},{type:'number',message:'年龄必须为数字值'}]">
					<el-input type="age" v-model="numberValidateForm.age" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<el-form-item>
				<el-button label="提交" @click="submitForm(numberValidateForm)"></el-button>
				<el-button label="重置" @click="resetForm(numberValidateForm)"></el-button>
			</el-form-item>
		</div>
		<div class="form3">

		</div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				dynamicValidateForm: {
					domains: [{
						value: ''
					}],
					email: ''
				},
				numberValidateForm:{
					age:''
				}
			};
		},
		methods: {
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if(valid) {
						alert('submit!');
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
			removeDomain(item) {
				var index = this.dynamicValidateForm.domains.indexOf(item)
				if(index !== -1) {
					this.dynamicValidateForm.domains.splice(index, 1)
				}
			},
			addDomain() {
				this.dynamicValidateForm.domains.push({
					value: '',
					key: Date.now()
				});
			}
		}
	}
</script>

<style>

</style>